package com.cndongtai.controller;

import java.io.IOException;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import com.cndongtai.constant.SystemConstant;

public class BaseController {
	
	public static final String SUCCESS = "00";
	
	public static final String FAILED = "11";
	
	@Autowired
	public HttpServletRequest request;
	
	@Autowired
	public HttpServletResponse response;
	
	@Resource(name="messageSourceXX")
	private ReloadableResourceBundleMessageSource messageSource;
	
	public final Logger log = Logger.getLogger(this.getClass());
	
	public void setMessageSource(ReloadableResourceBundleMessageSource messageSource) {
		this.messageSource = messageSource;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	/**
	 * 获取请求参数
	 * @param paramName
	 * @return
	 */
	public String getValue(String paramName) {
		return request.getParameter(paramName);
	}
	
	/**
	 * 获取批量请求参数
	 * @param paramName
	 * @return
	 */
	public String[] getValues(String paramName) {
		return request.getParameterValues(paramName);
	}
	
	/**
	 * 获取资源文件信息
	 * @param messageId
	 * @param params
	 * @return
	 */
	public String getMessage(String messageId, String[] params) {
		if(null==params) {
			params = new String[]{};
		}
		
		String language = (String) request.getSession().getAttribute(SystemConstant.LANGUAGE);
		Locale local = null;
    	if("zh".equals(language)) {
    		local = new Locale("zh","CN");
    	}else {
    		local = new Locale("en","US");
    	}
		
		try {
			return messageSource.getMessage(messageId, params, local);
		}catch(Exception e) {
			log.error(e.getMessage());
		}
		
		return messageId;
	}
	
	public void writeData(Object data){
        try{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(data);
        }catch(IOException e){
            log.error(e.getMessage());
        }finally{
            try{
                response.getWriter().close();
            }catch(IOException e){
                log.error(e.getMessage());
            }
        }
    }


}
